/* SOUND.C
 * Sound effect routines
 *************
 * 29.08.2000 : Toni R„s„nen
 *              modifications/documentation for open source
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include "mixer.h"
#include "mod.h"
#include "pakfile.h"
#include "sound.h"


char soundfiles[10][14] =
       { "outfit.raw",
         "goodnews.raw",
         "badnews.raw",
         "timetick.raw",
         "quake.raw",
         "bell.raw",
         "muledeth.raw",
         "product.raw",
           // foobar sounds begin ; no such sounds actually exists,
           // just to cause headache to potential cheater-hackers...
         "fuck_you.raw",
         "cheater.raw"};

char *sounds[20];
int soundlen[20];
int currchan;

int snd_curradx[32];
int snd_currsample[32];
int snd_currfreq[32];

void load_sounds()
{  int i;
   FILE *tied;

   for (i = 0; i < SND_COUNT; i++)
     {  tied = ffopen (soundfiles[i],"rb");

        if (tied)
          {  ffseek (tied,0,SEEK_END);
             soundlen[i] = fftell(tied);

             ffseek (tied,0,SEEK_SET);

             sounds[i] = (char*) malloc (soundlen[i]);

             fread (sounds[i], soundlen[i],1, tied);

             ffclose (tied);
          }
     }

   currchan = 16;

}

void playpartial_stream()
{  int chn,l,offs,sam;
   chn = intfromchannel;
   
   sam = snd_currsample[chn];

   snd_curradx[chn] += 16384;
   offs = snd_curradx[chn];

   l = soundlen[sam];

   l -= offs;
   if (l < 16384)
     {  sndendfunction[chn] = NULL;
     }
   else
     {  l = 16384;
     }

   mix_playsound (chn, sounds[sam]+offs, 0,-1, l, snd_currfreq[chn]);
}

void play_partial (int currchan, int snro, int freq)
{  int l;
   l = soundlen[snro];

   if (l > 16384)
     {  l = 16384;
        sndendfunction[currchan] = playpartial_stream;
        snd_curradx[currchan] = 0;
        snd_currsample[currchan] = snro;
        snd_currfreq[currchan] = freq;
     }
   else
     {  sndendfunction[currchan] = NULL;
     }
   mix_playsound(currchan, sounds[snro], 0,-1, l, freq);
}

void playsound(int nro, int freq)
{  if ( (nro < 0) || (nro >= SND_COUNT) ) return; // whoops...

   if (sounds[nro] == NULL) return; // double whoops...

   currchan++;
   if (currchan >= 20) currchan = 16; // 4 rotating channels for sounds

   mix_balance[currchan] = 7;
   mix_setvolume(currchan, sfxvolume);
   play_partial (currchan, nro, freq);
}

void release_sounds()
{  int i;
   for (i = 0; i < SND_COUNT; i++)
     {  if (sounds[i])
          { free (sounds[i]); sounds[i] = NULL; }
     }
}
